<template>
  <div class="echart-bmap_wrapper">
    <div class="btn">
      <el-button type="primary" @click="goBack" size="mini">全国</el-button>
    </div>
    <div class="bmap-box" id="bmapChartBox"></div>

    <div
      class="popWin"
      v-if="popShow"
      :style="{ left: popLeft + 'px', top: popTop + 'px' }"
    >
      <div class="popWins">
        <div class="titleInfos">
          <p class="cityName">{{ name }}工厂</p>
          <span class="pop_close" @click="popShow = false">关闭</span>
        </div>
        <div class="popLine"></div>
        <div class="infoBody">
          <!-- <basic-table
            class="homeTable"
            :TableHeaderList="TableHeaderList"
            :tableData="tableData"
            :hasPagination="false"
            :tableHeight="220"
            :rowHeight="20"
          ></basic-table> -->
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";

// import basicTable from "@/components/basicComponents/basicTable.vue";
import * as echarts from "echarts";
// import * as basicDataApi from "@/api/basicData.js";
import { listArea } from "@/api/system/area.js";
import provinceMapData from "../../../public/json/中华人民共和国_省.json";
import provinceMapData1 from "../../../public/中华人民共和国_市.json";
// import provinceMapData2 from "../../../public/json/100000/110000.geoJson";
import axios from "axios";
import {
  listPoint,
  getPoint,
  delPoint,
  addPoint,
  updatePoint,
} from "@/api/system/point";
const router = useRouter();
// 响应式数据
const pointData = ref([]);
const provinceCodeData = ref([]);
const provinceCodeData1 = ref([]);
const mapStack = ref([]);
const nowChooseData = ref([]);
const popShow = ref(false);
const popLeft = ref(0);
const popTop = ref(0);
const name = ref("");
const TableHeaderList = ref([]);
const tableData = ref([]);
const myChart = ref(null);
const gatewayPointData = reactive({});

// ECharts 配置
const option = reactive({
  tooltip: {
    trigger: "item",
    formatter: (params) => {
      return `<div style="font-size:14px;color:#666;">
        <div style="font-weight:bold;color:#409eff;">${params.name}</div>
       
      </div>`;
    },
  },
  geo: [
    {
      map: "js",
      aspectScale: 0.9,
      roam: true,
      zoom: 1.2,
      center: [116.405285, 39.904989],
      viewControl: {
        // 3D视角控制
        distance: 80,
        alpha: 30,
        beta: 30,
        autoRotate: true,
        autoRotateAfterStill: 3,
        rotateSensitivity: 1.5,
      },
      label: {
        normal: {
          show: true,
          textStyle: {
            color: "#fff",
            fontSize: 14,
            textShadow: "2px 2px 4px rgba(0,0,0,0.5)",
          },
        },
        emphasis: {
          textStyle: { color: "#fff", fontSize: 16, fontWeight: "bold" },
        },
      },
      itemStyle: {
        areaColor: {
          type: "linear",
          x: 0,
          y: 0,
          x2: 1,
          y2: 1,
          colorStops: [
            {
              offset: 0,
              color: "#0f2c5c",
            },
            {
              offset: 1,
              color: "#1d4b8f",
            },
          ],
        },
        borderColor: "#4e9bff",
        borderWidth: 1.5,
        shadowColor: "rgba(78,155,255,0.5)",
        shadowBlur: 15,
        shadowOffsetX: 2,
        shadowOffsetY: 4,
      },
      emphasis: {
        itemStyle: {
          areaColor: "#2470dc",
          borderWidth: 2,
          shadowColor: "rgba(78,155,255,0.8)",
          shadowBlur: 25,
        },
        label: {
          show: true,
          color: "#fff",
          fontSize: 16,
          fontWeight: "bold",
        },
      },
      light: {
        main: {
          intensity: 1.2,
          shadow: true,
          shadowQuality: "high",
          alpha: 30,
          beta: 150,
        },
        ambient: {
          intensity: 0.3,
        },
      },
    },
  ],

  series: [
    {
      type: "effectScatter",
      coordinateSystem: "geo",
      showEffectOn: "render",
      // rippleEffect: { period: 10, scale: 6, brushType: "fill" },
      rippleEffect: {
        period: 8, // 减小波动周期
        scale: 3, // 缩小涟漪范围
        brushType: "stroke", // 描边类型
        number: 1, // 单层涟漪
      },
      symbol: "circle",
      label: {
        show: false, // 关闭标签显示
      },
      zlevel: 10,
      hoverAnimation: true,
      itemStyle: {
        normal: {
          color: (params) => {
            const colors = {
              "7300网关": "red",
              "700网关": "yellow",
              "5300网关": "green",
            };
            return colors[params.name] || "pink";
          },
          shadowBlur: 5, // 减小阴影模糊
          shadowColor: "rgba(0, 0, 0, 0.3)",
        },
        emphasis: {
          // 高亮状态样式
          color: "#FFF", // 高亮时变白
          borderColor: "#409EFF",
          borderWidth: 1,
        },
      },
      data: [],
    },
  ],
});

// 方法

// 初始化点位信息
const initPointData = async (pointAddress, type) => {
  try {
    let res = await listPoint({
      pageNum: 1,
      pageSize: 100000,
    });
    if (res.code === 200) {
      const data = res.rows.map((item) => ({
        name: item.pointName,
        value: [item.lon, item.lat],
        address: item.pointAddress || "",
        pointId: item.id,
      }));
      Object.keys(gatewayPointData).forEach((key) => {
        delete gatewayPointData[key];
      });
      if (pointAddress) {
        gatewayPointData[pointAddress] = [];
        data.forEach((point) => {
          // console.log('point',point.address.match(/^[^/]+/)[type],pointAddress)
          console.log("point", point.address.split("/")[type - 1]);
          if (point.address.split("/")[type - 1] == pointAddress) {
            console.log("point", point.address.match(/^[^/]+/)[type - 1]);
            gatewayPointData[pointAddress].push(point);
          }
        });
      } else {
        gatewayPointData["中国"] = data;
      }
    }
    console.log("更新地图数据", gatewayPointData);
  } catch (error) {
    console.log("error", error);
  }
};
// 遍历对象
const getProvinceCode = () => {
  provinceCodeData.value = provinceMapData.features.map((item) => ({
    name: item.properties.name,
    coordinateCenter: item.properties.center,
    cityCode: item.properties.adcode,
  }));
};
const getCountyCode = () => {
  provinceCodeData1.value = provinceMapData1.features.map((item) => ({
    name: item.properties.name,
    coordinateCenter: item.properties.center,
    cityCode: item.properties.adcode,
  }));
};

// 返回
const goBack = () => {
  popShow.value = false;
  mapStack.value = [provinceMapData];
  drawMap(provinceMapData, 0, [126.82862, 49.296976]);
};
// 设置地图中心点
const setMapCenterZoomData = (data, zoom, center, type) => {
  option.series[0].data = data;
  option.geo[0].zoom = zoom;
  option.geo[0].center = center;
  if (!type) {
    option.geo[0].layoutSize = mapStack.value.length <= 1 ? "100%" : "";
    option.geo[0].layoutCenter =
      mapStack.value.length <= 1 ? ["85%", "20%"] : [];
  } else {
    option.geo[0].layoutSize = mapStack.value.length <= 1 ? "100%" : "";
    option.geo[0].layoutCenter =
      mapStack.value.length <= 1 ? ["50%", "50%"] : [];
  }
};
// 地图下钻
const drawMap = async (json, type = 0, city, cityName) => {
  if (!document.getElementById("bmapChartBox")) return;

  echarts.dispose(document.getElementById("bmapChartBox"));
  const chart = echarts.init(document.getElementById("bmapChartBox"));
  myChart.value = chart;
  echarts.registerMap("js", json);
  console.log("type", type);
  if (type && type !== 0) {
    await initPointData(cityName, type);
    console.log("安徽省", gatewayPointData);
    const points = gatewayPointData[cityName];
    setMapCenterZoomData(points, 1.2, city, type);
  } else {
    await initPointData();
    console.log("中国", gatewayPointData);
    const points = gatewayPointData["中国"];
    setMapCenterZoomData(points, 1, [126.82862, 49.296976]);
  }
  chart.setOption(option);
  chart.off("click");
  // 地图点位点击事件
  chart.on("click", (param) => {
    // console.log("点击点位", param.componentType);
    if (param.componentType === "geo") {
      handleMapClick(param);
    } else if (param.componentType === "series") {
      handlePointClick(param);
    }
  });
};
// 地图点击事件
const handleMapClick = (param) => {
  if (param.componentType !== "geo") return;

  popLeft.value = param.event.event.offsetX;
  popTop.value = param.event.event.offsetY;
  name.value = param.name;
  // popShow.value = true;

  if (mapStack.value.length >= 3) {
    console.warn("No more data available");
    return;
  }
  let type = 1;
  let cityCode = findCityCode(param.name);
  if (!cityCode) {
    type = 2;
    cityCode = findCountyCode(param.name);
  }
  let cityLocation = findCityLocation(param.name);
  if (!cityLocation) cityLocation = findCountyLocation(param.name);
  if (!cityCode) {
    type = 3;
    // router.push({
    //   path: "/statistics",
    //   query: {
    //     name: param.name,
    //   },
    // });
  }
  if (cityCode) getHomeMapData(param.name, cityCode, cityLocation, type);
};
// 查找城市编码
const findCityCode = (cityName) => {
  const dataSource =
    mapStack.value.length <= 1 ? provinceCodeData.value : nowChooseData.value;
  return dataSource.find((i) => i.name === cityName)?.cityCode;
};
const findCityLocation = (cityName) => {
  const dataSource =
    mapStack.value.length <= 1 ? provinceCodeData.value : nowChooseData.value;
  return dataSource.find((i) => i.name === cityName)?.coordinateCenter;
};
const findCountyCode = (cityName) => {
  const dataSource =
    mapStack.value.length <= 1 ? provinceCodeData1.value : nowChooseData.value;
  return dataSource.find((i) => i.name === cityName)?.cityCode;
};
const findCountyLocation = (cityName) => {
  const dataSource =
    mapStack.value.length <= 1 ? provinceCodeData1.value : nowChooseData.value;
  return dataSource.find((i) => i.name === cityName)?.coordinateCenter;
};
// 获取地图数据
const getHomeMapData = async (city, cityCode, cityLocation, type) => {
  try {
    const res = await listArea({
      areaCode: `${cityCode}`,
    });
    if (res) {
      // const code = `${cityCode}`.replace(/\d{2}$/, "00");
      let data;
      if (type === 1) {
        data = await axios.get(`/json/100000/${cityCode}.geoJson`);
      } else if (type === 2) {
        const result = Number(String(cityCode).match(/^\d{2}/) + "0000");
        data = await axios.get(`/json/100000/${result}/${cityCode}.geoJson`);
      } else {
      }
      // const data = await axios.get(`/json/100000/${cityCode}.geoJson`);
      drawMap(data.data, type, cityLocation, res.rows[0].name);
    }
  } catch (err) {
    console.error("Failed to load map data:", err);
  }
};

// 点位点击事件
const handlePointClick = (param) => {
  console.log("点击点位:", param);
  router.push({
    path: "/statistics",
    query: {
      pointId: param.data.pointId,
      name: param.name,
    },
  });
};
// 生命周期
onMounted(() => {
  Promise.all([initPointData()]).then(() => {
    drawMap(provinceMapData, 0, [126.82862, 49.296976]);
    getProvinceCode();
    getCountyCode();
    mapStack.value = [provinceMapData];
  });
});

onBeforeUnmount(() => {
  if (myChart.value) myChart.value.dispose();
});
</script>

<style lang="scss" scoped>
.echart-bmap_wrapper {
  position: relative;

  .btn {
    position: absolute;
    left: 20px;
    top: 20px;
    z-index: 1;
  }

  .bmap-box {
    width: 100%;
    height: 85vh;
  }

  .popWin {
    position: absolute;
    left: 0;
    top: 0;
    background: #00305c;
    background-size: 100% 100%;
    width: 408px;
    height: 300px;
    z-index: 100;

    .popLine {
      width: 340px;
      height: 1px;
      background: linear-gradient(
        90deg,
        #ffffff 0%,
        rgba(255, 255, 255, 0) 100%
      );
      opacity: 0.3;
      margin-left: 30px;
    }

    .titleInfos {
      text-align: center;
      margin-left: 30px;
      font-size: 22px;
      font-family: YouSheBiaoTiHei;
      font-weight: 400;
      color: #00fdfe;
      height: 50px;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      flex-wrap: nowrap;
      flex-direction: row;
      align-content: flex-start;
      .pop_close {
        color: #bbb;
        cursor: pointer;
        padding: 5px;
        font-size: 12px;
        position: absolute;
        top: 5px;
        right: 10px;
      }
    }
  }

  .infoBody {
    width: 100%;
    padding: 3%;
    .homeTable {
      border: 1px solid #0376ae;
      border-radius: 10px;
    }
  }
  .infoBody ::v-deep .plTableBox .el-table .cell.el-tooltip {
    border-bottom: 1px solid #086896;
  }
  .infoBody ::v-deep .el-table,
  .el-table__expanded-cell {
    background-color: transparent;
  }
  .infoBody ::v-deep .el-table tr {
    // background-color: transparent!important;
    background-color: #0b4d73;
  }
  .infoBody ::v-deep .el-table--enable-row-transition .el-table__body td,
  .el-table .cell {
    background-color: transparent;
  }
  .el-table::before {
    //去除底部白线
    left: 0;
    bottom: 0;
    width: 100%;
    height: 0px;
  }
  .infoBody ::v-deep .plTableBox .el-table .el-table__header th {
    background-color: transparent;
  }
  .infoBody
    ::v-deep
    .plTableBox
    .el-table--enable-row-hover
    .el-table__body
    tr:hover
    > td {
    background-color: rgba(0, 77, 167, 1);
  }
  .infoBody ::v-deep .plTableBox .el-table--border td,
  .infoBody ::v-deep .plTableBox .el-table--border th,
  .infoBody
    ::v-deep
    .plTableBox
    .el-table__body-wrapper
    .el-table--border.is-scrolling-left
    ~ .el-table__fixed {
    border: none;
    color: #4daad3;
  }
  .infoBody ::v-deep .plTableBox .el-table--medium td {
    padding: 0;
  }
  .infoBody ::v-deep .plTableBox .el-table__header-wrapper {
    background-color: transparent;
  }
  .infoBody
    ::v-deep
    .plTableBox
    .el-table--striped
    .el-table__body
    tr.el-table__row--striped
    td {
    background-color: #103c5c;
  }
}
</style>
<style lang="scss" scoped>
.echart-bmap_wrapper {
  position: relative;
  // height: 100vh;
  // background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .title {
      color: #2c3e50;
      font-size: 24px;
      text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
      margin: 0;
    }

    .back-btn {
      background: linear-gradient(45deg, #409eff, #79bbff);
      border: none;
      border-radius: 15px;
      box-shadow: 0 4px 6px rgba(50, 50, 93, 0.11);
      transition: all 0.3s;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 7px 14px rgba(50, 50, 93, 0.2);
      }
    }
  }

  .dashboard {
    display: grid;
    grid-template-columns: 280px 1fr;
    gap: 20px;
    height: calc(100vh - 100px);

    .stats-card {
      display: flex;
      flex-direction: column;
      gap: 15px;

      .card-item {
        padding: 20px;
        border-radius: 12px;
        color: white;
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        transition: transform 0.3s;

        &:hover {
          transform: translateY(-5px);
        }

        h3 {
          margin: 0 0 10px 0;
          font-size: 16px;
        }

        .number {
          font-size: 24px;
          font-weight: bold;
          margin: 0;
        }

        &.bg-blue {
          background: linear-gradient(45deg, #409eff, #79bbff);
        }
        &.bg-green {
          background: linear-gradient(45deg, #67c23a, #85ce61);
        }
        &.bg-orange {
          background: linear-gradient(45deg, #e6a23c, #ebb563);
        }
      }
    }

    .bmap-box {
      background: white;
      border-radius: 12px;
      box-shadow: 0 10px 20px rgba(0, 0, 0, 0.15);
      overflow: hidden;
    }
  }

  .popWin {
    /* 优化后的弹窗样式 */
    background: rgba(255, 255, 255, 0.95);
    border-radius: 12px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.2);

    .titleInfos {
      background: linear-gradient(90deg, #409eff, #79bbff);
      border-radius: 12px 12px 0 0;
      padding: 15px 20px;

      .cityName {
        color: white;
        margin: 0;
        font-size: 18px;
      }
    }

    .popLine {
      background: linear-gradient(90deg, #79bbff, transparent);
      height: 2px;
    }

    .infoBody {
      padding: 15px;
    }
  }
}
</style>
<style lang="scss" scoped>
// 添加光标动画效果
.echart-bmap_wrapper {
  .bmap-box canvas {
    cursor: pointer;
    @keyframes pulse {
      0% {
        transform: scale(0.9);
        opacity: 0.7;
      }
      50% {
        transform: scale(1.1);
        opacity: 1;
      }
      100% {
        transform: scale(0.9);
        opacity: 0.7;
      }
    }

    .echarts-effectscatter-effect {
      animation: pulse 1.5s infinite;
    }
  }
}
</style>
